// 运行时配置

import { history } from '@umijs/max';
import { message } from 'antd';
import type { RequestConfig } from 'umi';
import settings from '../config/defaultSettings';
import RightContent from './components/RightContent';
import { getUser } from './pages/settings/assets';

export const request: RequestConfig = {
	timeout: 1000,

	errorConfig: {
		errorHandler: (e: any) => {
			const { status } = e?.response ?? {};

			if (status === 401) {
                message.error('身份认证失败');
                history.push('/login');
            }

			if (status === 504 ) {
				message.error('请求超时，请检查网络');
			}
		},
	},

	requestInterceptors: [
		(config: Record<string, any>) => {
			const token = localStorage.getItem('vehicle_token') || '';
			if (token) {
				config.headers = {
					...config.headers,
					Authorization: `Bearer ${token}`,
				};
			}
			return config;
		},
	],
};

export async function getInitialState(): Promise<Record<string, any>> {
	try {
		const { name, ...userInfo } = await getUser();
		return { name, userInfo };
	} catch (error) {
		return { name: 'Unknown', userInfo: {} };
	}
}

export const layout = ({ initialState }: any) => {
	const { userInfo } = initialState;
	return {
		...settings,
		logo: 'https://img.alicdn.com/tfs/TB1YHEpwUT1gK0jSZFhXXaAtVXa-28-27.svg',
		menu: {
			locale: false,
		},
		rightContentRender: () => {
			return <RightContent {...userInfo} />;
		},
	};
};
